package com.friend.controller.admin;

import com.common.core.controller.BaseController;
import com.common.core.domain.R;
import com.common.core.enums.ResultCode;
import com.friend.manager.ElasticsearchIndexManager;
import com.friend.manager.QuestionCacheManager;
import com.friend.service.question.impl.QuestionServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/question")
@Tag(name = "题目管理接口")
@Slf4j
public class QuestionAdminController extends BaseController {

    @Autowired
    private QuestionServiceImpl questionService;
    
    @Autowired
    private QuestionCacheManager questionCacheManager;
    
    @Autowired
    private ElasticsearchIndexManager elasticsearchIndexManager;

    @PostMapping("/sync")
    @Operation(summary = "同步ES和Redis", description = "强制同步ES索引和Redis缓存")
    public R<String> syncESAndRedis() {
        try {
            // log.info("开始同步ES和Redis");
            
            // 1. 同步ES索引
            questionService.refreshQuestion();
            // log.info("ES索引同步完成");
            
            // 2. 同步Redis缓存
            questionCacheManager.refreshCache();
            // log.info("Redis缓存同步完成");
            
            return R.success("ES和Redis同步成功");
        } catch (Exception e) {
            log.error("同步ES和Redis失败", e);
            return R.failed(ResultCode.FAILED);
        }
    }
    
    @PostMapping("/rebuild-index")
    @Operation(summary = "重建ES索引", description = "删除旧索引并重新创建，然后同步所有数据")
    public R<String> rebuildIndex() {
        try {
            // log.info("开始重建ES索引");
            
            boolean success = elasticsearchIndexManager.recreateIndexAndSyncData();
            
            if (success) {
                // log.info("ES索引重建成功");
                return R.success("ES索引重建成功");
            } else {
                // log.error("ES索引重建失败");
                return R.failed(ResultCode.FAILED.getCode(), "ES索引重建失败");
            }
        } catch (Exception e) {
            // log.error("重建ES索引异常", e);
            return R.failed(ResultCode.FAILED.getCode(), "ES索引重建异常: " + e.getMessage());
        }
    }
    
    @GetMapping("/index-stats")
    @Operation(summary = "查看索引状态", description = "获取ES索引统计信息")
    public R<String> getIndexStats() {
        try {
            String stats = elasticsearchIndexManager.getIndexStats();
            return R.success(stats);
        } catch (Exception e) {
            log.error("获取索引统计信息失败", e);
            return R.failed(ResultCode.FAILED.getCode(), "获取索引统计信息失败: " + e.getMessage());
        }
    }
}
